package com.taobao.shopcart.listeners;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.shopcart.model.dto.OrderDto;
import com.taobao.shopcart.model.dto.OrderDtos;
import com.taobao.shopcart.service.ShopCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class MqListener {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private ShopCartService shopCartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.order", durable = "true"),
            exchange = @Exchange(name = "taobao.direct", type = ExchangeTypes.DIRECT),
            key = {"order"}))
    public void listenDirectOrder(Message message) {
        try {
            // 将消息反序列化为 Map
            Map<String, Object> msg = objectMapper.readValue(message.getBody(), Map.class);
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 Map 转换为 OrderDto 对象
            OrderDtos orderDtos = objectMapper.convertValue(msg, OrderDtos.class);
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orderDtos, orderDto);

            // 模拟消息处理逻辑
            shopCartService.submitOrder(orderDto, orderDtos.getUserId());
            System.out.println("消息已成功处理并确认");
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("消息处理失败，原因：" + e.getMessage());
        }
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.order", durable = "true"),
            exchange = @Exchange(name = "taobao.direct", type = ExchangeTypes.DIRECT),
            key = {"test"}
    ))
    public void listenDirectOrderTest(String msg) throws InterruptedException {
        System.out.println("消费者orderTest 收到了 direct.orderTest的消息：【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.msg", durable = "true"),
            exchange = @Exchange(name = "taobao.direct", type = ExchangeTypes.DIRECT),
            key = {"msg"}
    ))
    public void listenDirectMsg(String msg) throws InterruptedException {
        System.out.println("消费者msg 收到了 direct.msg的消息：【" + msg + "】");
    }

}
